package controllers

import (
	beego "github.com/beego/beego/v2/server/web"
	"path/filepath"
	"strings"
	"xinhua_bookstore/models"
)

type BookController struct {
	beego.Controller
}

func (c *BookController) Add() {
	file, header, err := c.GetFile("img")
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"code": 500,
			"msg":  "请选择要上传的图片",
		}
		c.ServeJSON()
		return
	}
	defer file.Close()
	if header.Size > 2*1024*1024 {
		c.Data["json"] = map[string]interface{}{
			"code": 500,
			"msg":  "图片过大",
		}
		c.ServeJSON()
		return
	}
	set := map[string]bool{
		".jpg":  true,
		".png":  true,
		".jpeg": true,
	}
	suffix := strings.ToLower(filepath.Ext(header.Filename))
	if set[suffix] == false {
		c.Data["json"] = map[string]interface{}{
			"code": 500,
			"msg":  "图片格式不正确",
		}
		c.ServeJSON()
		return
	}
	path := "static/img/" + header.Filename
	c.SaveToFile("img", path)
	name := c.GetString("name")
	content := c.GetString("content")
	var books models.Book
	books.Name = name
	books.Content = content
	books.Img = "http://127.0.0.1:8080/" + path
	err = books.Add()
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"code": 500,
			"msg":  "添加失败",
		}
		c.ServeJSON()
		return
	}
	c.Data["json"] = map[string]interface{}{
		"code": 200,
		"msg":  "添加成功",
	}
	c.ServeJSON()
	return
}
